/**
 * Created by Daniel on 2017/8/24.
 */
'use strict';
var router = require('express').Router();
var AV = require('leanengine');
var crypto = require('crypto')
var functionTool = require('../queryFun/functionTool');
var Todo = AV.Object.extend('Todo');
var gm = require('gm');
var fs = require('fs');
var im = require('imagemagick');
var multiparty = require('multiparty');
var qn = require('../qiniu/upload');
var imageMagick = gm.subClass({imageMagick: true});
var path = process.cwd();
var uuid = require('node-uuid');
var WXPay = require('../cloud/wx/wxPay');
var common = require('../cloud/common');
var apis = require('../cloud/lib/apis');
var message = require('../cloud/lib/message');
var async = require('async');
var redisServer = require('../cloud/redis/redisServer');
var keys = require('../cloud/lib/keys');
var qnAndroid = require("../qiniu/androidUpload");
var qiniu = require("qiniu")
var qiniu1 = require("qiniu/index")
var upload = require('../queryFun/fileuploads');
var xlsx = require('node-xlsx');
// let uuid = require('node-uuid')kkkkk


router.post('/findUser', function (req, res) {
    var key = req.body.key;
    var query = new AV.Query('_User');
    query.equalTo("nickName", key);
    query.first().then(function (result) {
        var temObj = {};
        temObj["objectId"] = result.id;
        temObj["sex"] = result.get("sex");
        temObj["uid"] = result.get("uid");
        temObj["username"] = result.get("username");
        temObj["regisFrom"] = result.get("regisFrom");
        temObj["gender"] = result.get("userAvatar") ? result.get("userAvatar").url() : "";
        temObj["mobilePhoneNumber"] = result.get("mobilePhoneNumber");
        temObj["live_authority"] = result.get("live_authority");
        temObj["verify_authority"] = result.get("verify_authority");
        temObj["createAt"] = result.get("createAt");
        temObj["nickName"] = result.get("nickName");
        temObj["phoneRegVerify"] = result.get("phoneRegVerify");
        res.send(JSON.stringify(temObj));
    })
});

router.post('/usersInformation', function (req, res, next) {
    var nickName = req.body.nickName;
    var mobilePhoneNumber = req.body.mobilePhoneNumber;
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var uid = req.body.uid;
    functionTool.userInformation(nickName, objectId, mobilePhoneNumber, uid, page, num,'', function (err, result) {
        res.send(JSON.stringify(result));
    })
});


router.get('/edit', function (req, res) {
    var id = req.query.id;
    functionTool.userInformation('', id, '', '', '', '','', function (err, result) {
        res.render("edit/edit", {result: result});
    });
});

router.get('/liveGuanlianQuestion', async function (req, res) {
    var id = req.query.objectId;


    let params = {}
    params.page = Number(0) + 1;;
    params.pageSize = 1000;

    let result = await functionTool.getQuestion(params);



    res.render("live/questionList", {result: result,liveId:id});
});

router.post('/guanlianQuestionLive',  function (req, res) {
    var id = req.body.objectId;
    var liveId = req.body.liveId;
    let Live = AV.Object.createWithoutData('Live_room', liveId);
    if(id){
        Live.set('questionOId', id);
        Live.set('questionObj', {"__type": "Pointer", className: "Question", objectId: id});
    }else{
        Live.set('questionOId', null);
        Live.set('questionObj', null);
    }
// 保存到云端
    Live.save().then(function (data) {


        res.send("1");
    },function(ee){
        res.send("0");

    })



});

router.post('/updataUser', function (req, res) {
    req.params = req.body;
    functionTool.updataUser(req, function (error, result) {
        res.send();
    })
});

router.post('/addUser', function (req, res) {
    req.params = req.body;
    functionTool.updataUser(req, function (error, result) {
        res.send();
    })
});


router.get('/remove', function (req, res) {
    var id = req.query.id;
});

router.post('/userStatus', function (req, res, next) {
    var name = req.body.name;
    var tel = req.body.tel;
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var status = req.body.status;
    if (name == undefined && tel == undefined && objectId == undefined && status == undefined) {
        status = '3';
    }
    functionTool.userStatus(name, tel, objectId, status, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/userStatusEdit', function (req, res) {
    var id = req.query.id;
    functionTool.userStatus('', '', id, '', '', '', function (err, result) {
        res.render("edit/userStatusEdit", {result: result});
    });
});

router.post('/updataUserStatus', function (req, res) {
    req.params = req.body;
    functionTool.updataUserStatus(req, function (error, result) {
        res.send();
    })
});
router.post('/shopVerifyManger', function (req, res) {
    var params = req.body;
    functionTool.getShopVerifyInfo(params, function (result) {
        res.send(JSON.stringify(result));
    })
});
router.get('/shopVerifyMangerEdit', function (req, res) {
    res.render("mall/shopVerifyMangerEdit", {});
});
router.get('/shopVerifyMangerRefuse', function (req, res) {
    res.render("mall/shopVerifyMangerRefuse", {});
});
router.post('/shopVerifyMangerEditHandle', function (req, res) {
    var params = req.body;
    functionTool.shopVerifyMangerEditHandle(params, function (result) {
        res.send(JSON.stringify(result));
    });
});
router.post('/shopManger', function (req, res, next) {
    var type = req.body.dept_id;
    var name = req.body.name;
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.shopInformation(objectId, name, type, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/shopMangerEdit', function (req, res) {
    var id = req.query.id;
    functionTool.shopInformation(id, '', '', '', '', function (err, result) {
        functionTool.shopTypeSelect(function (shopType) {
            result.shopTree = JSON.stringify(shopType);
            res.render("mall/shopMangerEdit", {result: result});
        })
    });
});

router.get('/shopMangerAdd', function (req, res) {
    functionTool.shopTypeSelect(function (shopType) {
        res.render("mall/shopMangerAdd", {result: JSON.stringify(shopType)});
    })
});
//tecShop
router.post('/getTECShopGoodsList',async function (req,res) {
    let page = req.body.pageIndex;
    page = Number(page)+1;
    let num = req.body.pageSize;
    let classify = req.body.classify;
    let result = await functionTool.getTECShopGoodsList(page,num,classify);
    res.send(JSON.stringify(result))
})
router.get('/tecShopAdd',function (req,res) {
    functionTool.getTECShopClassify(tecShopType=>{
        res.render("mall/tecShopAdd",{result: JSON.stringify(tecShopType)});
    })
})

router.post('/addTECShopGoods',async function (req,res){
    let shopGoodsOId = req.body.shopGoodsOId;
    let price = req.body.price;
    price = Number(price);
    let score = req.body.score;
    score = Number(score);
    let freight = req.body.freight;
    freight = Number(freight);
    let count = req.body.count;
    count = Number(count);
    let classify = req.body.classify;
    let presentScore = req.body.presentScore;
    presentScore = Number(presentScore);
    let superiorMoney = req.body.superiorMoney;
    superiorMoney = Number(superiorMoney);
    let superiorSuperiorMoney = req.body.superiorSuperiorMoney;
    superiorSuperiorMoney = Number(superiorSuperiorMoney);
    let ancestorsMoney = req.body.ancestorsMoney;
    ancestorsMoney = Number(ancestorsMoney);
    let superiorScore = req.body.superiorScore;
    superiorScore = Number(superiorScore);
    let superiorSuperiorScore = req.body.superiorSuperiorScore;
    superiorSuperiorScore = Number(superiorSuperiorScore);
    let ancestorsScore = req.body.ancestorsScore;
    ancestorsScore = Number(ancestorsScore);

    let result = await functionTool.addTECShopGoods(shopGoodsOId,price,score,freight,count,classify,presentScore,superiorMoney,superiorSuperiorMoney,ancestorsMoney,superiorScore,superiorSuperiorScore,ancestorsScore);
    if(result){
        res.send("1");
    }else{
        res.send("0");
    }

})
router.get('/tecShopEdit',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.selectTECShopGoods(objectId);
    res.render('mall/tecShopEdit',{result:result});

})
router.post('/editTECGoodsShop',async function (req,res) {
    let objectId = req.body.objectId;
    let price = req.body.price;
    price = Number(price);
    let score = req.body.score;
    score = Number(score);
    let freight = req.body.freight;
    freight = Number(freight);
    let count = req.body.count;
    count = Number(count);
    let presentScore = req.body.presentScore;
    presentScore = Number(presentScore);
    let superiorMoney = req.body.superiorMoney;
    superiorMoney = Number(superiorMoney);
    let superiorSuperiorMoney = req.body.superiorSuperiorMoney;
    superiorSuperiorMoney = Number(superiorSuperiorMoney);
    let ancestorsMoney = req.body.ancestorsMoney;
    ancestorsMoney = Number(ancestorsMoney);
    let superiorScore = req.body.superiorScore;
    let superiorSuperiorScore = req.body.superiorSuperiorScore;
    superiorSuperiorScore = Number(superiorSuperiorScore);
    superiorScore = Number(superiorScore);
    let ancestorsScore = req.body.ancestorsScore;
    ancestorsScore = Number(ancestorsScore);
    let result = await  functionTool.editTECGoodsShop(objectId,price,score,freight,count,presentScore,superiorMoney,superiorSuperiorMoney,ancestorsMoney,superiorScore,superiorSuperiorScore,ancestorsScore);
    if(result){
        res.send("1");
    }else{
        res.send("0");
    }
})
router.post('/deleteTECShopGoods', function (req,res) {
    functionTool.deleteTECShopGoods(req,function (err,result) {
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})
router.post('/moveTECShopGoods', function (req,res) {
    functionTool.moveTECShopGoods(req.body,function (result) {
        // console.log(result);
        if (result == '10000') {
            res.send(result);
        } else {
            res.send();
        }
    });
})
//shopIntergation
router.post('/shopIntergation',async function (req,res) {
    let page = req.body.pageIndex;
    page = Number(page)+1;
    let num =  req.body.pageSize;
    let goodsName = req.body.goodsName;
    let goodsParentTypeID = req.body.goodsParentTypeID;
    let result = await functionTool.shopSearch(page,num,goodsName,goodsParentTypeID);
    res.send(JSON.stringify(result));
})
router.post('/moveScoreShopGoods', function (req,res) {
    functionTool.moveScoreShopGoods(req.body,function (result) {
        // console.log(result);
        if (result == '10000') {
            res.send(result);
        } else {
            res.send();
        }
    });
})

router.post('/moveTopScoreShopGoods', function (req,res) {
    functionTool.moveTopScoreShopGoods(req.body,function (result) {
        // console.log(result);
        if (result == '10000') {
            res.send(result);
        } else {
            res.send();
        }
    });
})
router.get('/intergationAdd',function (req,res) {
    functionTool.getScoreShopClassify(result=>{
        res.render("mall/shopIntergationAdd");
    })
})

router.post('/shopGoodSelect',async function (req,res) {
    let name = req.body.name;
    let objectId = req.body.objectId;
    let shopName = req.body.shopName;
    let shopId = req.body.shopId;
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await  functionTool.shopGoodSelect(objectId,name,shopName,shopId,page,num);
    res.send(JSON.stringify(result));
})

router.post('/addScoreGoodsShop',async function (req,res){
    let result = await functionTool.updateScoreGoods(req.body);
    if(result){
        res.send("1");
    }else{
        res.send("0");
    }
})
router.post('/addScoreGoodsShopForBatch',async function (req,res){
    // console.log(req.body)
  let result = await functionTool.addScoreGoodsShopForBatch(req.body);
  if(result){
    res.send("1");
  }else{
    res.send("0");
  }
})
router.post('/deleteShopIntergation', function (req,res) {
    functionTool.deleteShopIntergation(req,function (err,result) {
        console.log(result);
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})

router.get('/scoreGoodsEdit',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.selectScoreShopGoods(objectId);
    res.render('mall/shopIntergationEdit',{result:result});

})


router.post('/editScoreGoodsShop',async function (req,res) {
    let result = await  functionTool.editScoreGoodsShop(req.body);
    if(result){
        res.send("1");
    }else{
        res.send("0");
    }
})


//bestSellers
router.post('/bestSellersManage', async function (req, res) {
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await  functionTool.findShopRecommend(page, num);
    res.send(JSON.stringify(result));
})

router.get('/shopRecommendAdd', function (req, res) {
    res.render('mall/bestSellerAdd', {})
})

router.post('/addShopGoodRecommend', async function (req, res) {
    let shopGoodsOId = req.body.shopGoodsOId;
    let result = await functionTool.addShopGoodsRecommend(shopGoodsOId);
    if (result) {
        res.send("1");
    } else {
        res.send("0");
    }
})

router.get('/shopRecommendEdit', async function (req, res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.selShopGoodRecommend(objectId);
    result.objectId = objectId;
    res.render('mall/bestSellerEdit', {result: result})
})

router.post('/updateShopGoodRecommend', async function (req, res) {

    let status = req.body.status;
    let objectId = req.body.objectId;
    let result = await  functionTool.updShopGoodRecommend(objectId, status);
    if (result) {
        res.send("1");
    } else {
        res.send("2");
    }
})



router.post('/deleteShopRecommend', function (req, res) {
    functionTool.deleShopGoodRecommend(req, function (err, result) {
        console.log(result);
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})


router.post('/updataShopInformation', function (req, res) {
    req.params = req.body;
    functionTool.updataShopInformation(req, function (error, result) {
        res.send();
    })
});

router.post('/shopMangerTree', function (req, res) {
    functionTool.shopType(function (result) {
        res.send(JSON.stringify(result));
    })
});


// router.get('/shopMangerRemove',function (req,res) {
//     var id =req.query.objectId;
//     var status = req.query.status;
//     var Shop = AV.Object.createWithoutData('Shop_shop',id);
//     // 修改属性
//     Shop.set('status',status);
//     // 保存到云端
//     Shop.save().then(function (success) {
//             res.send("1");
//         },function (error) {
//             console.log(error);
//             res.send("0");
//         }
//     )
// });

router.post('/goodsMangerInformation', function (req, res) {
    // var sysCategory = req.body.dept_id;
    var goodsType = req.body.dept_id;
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var shopOId = req.body.shopOId;
    var title = req.body.title;
    var status = req.body.status;
    functionTool.goodsInformation(objectId, shopOId, title, goodsType, status, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});


router.get('/goodsEdit', function (req, res) {
    var id = req.query.id;
    var config = qn.config;
    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0,
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var token = putPolicy.uploadToken(mac);
    functionTool.goodsInformation(id, '', '', '', '', '', '', function (err, result) {
        functionTool.goodsTypeSelect(function (goodsTypesList) {
            // let shopGoodsPicArray1 = result.data[0].shopGoodsPicArray
            // console.log(shopGoodsPicArray1.length)
            // console.log(JSON.stringify(result.data[0].shopGoodsPicArray))
            res.render("mall/goodsMangerEdit", {
                result: result,
                goodsTypesList:JSON.stringify(goodsTypesList),
                objectId:id,
                domain: config.Domain,
                uptoken: token
            });
        })
    });
});
router.post('/getGoodsEditModelArray', function (req, res) {
    var id = req.body.objectId;
    // console.log(id)
    functionTool.getGoodsEditModelArray(id,resultModel=>{
        // console.log(JSON.stringify(result))
        res.send(JSON.stringify(resultModel))
    })

});
router.post('/updataGoods', function (req, res) {
    req.params = req.body;
    var price = parseInt(req.body.price);
    var discount = req.body.discount;
    var originalPrice = req.body.originalPrice;
    // var priceVaule = parseInt(originalPrice*discount/10);
    // if(priceVaule==price){
    functionTool.updataGoodsInformation(req, function (err, result) {
        if (!err) {
            res.send('1');
        } else {
            res.send('0');
        }
    })
    // }
})

router.post('/editGoods', async function (req, res) {
    req.params = req.body;
    // var models = JSON.parse(req.params.model);
    // var modelArray = await saveModelForUpdateGoods(goodsId, models);
    var price = parseInt(req.body.price);
    var discount = req.body.discount;
    var originalPrice = req.body.originalPrice;

    var objectId = req.params.objectId;
    if (objectId != "" && objectId != undefined && objectId != null) {
        var Shop = AV.Object.createWithoutData('Shop_goods', req.params.objectId);
    } else {
        var Shops = AV.Object.extend('Shop_goods');
        var Shop = new Shops();
        var shopObj = AV.Object.createWithoutData('Shop_shop', req.params.shopOId);
        var sellerObj = AV.Object.createWithoutData('_User', req.params.sellerOId);
        Shop.set('shopOId', req.params.shopOId);
        Shop.set('shopObj', shopObj);
        Shop.set('sellerOId', req.params.sellerOId);
        Shop.set('sellerObj', sellerObj);
        Shop.set("picName", picArr[0]);
    }
    // 修改属性
    Shop.set('title', req.params.title);
    Shop.set('promotePrice', Number(req.params.promotePrice));
    Shop.set('status', Number(req.params.status));
    Shop.set('groupBuying', Number(req.params.groupBuying));
    Shop.set('freePost', req.params.freePost);
    Shop.set('groupPrice', Number(req.params.groupPrice));
    Shop.set('saleNums', Number(req.params.saleNums));
    Shop.set('originalPrice', Number(req.params.originalPrice));
    Shop.set('price', Number(req.params.price));
    Shop.set('customize', Number(req.params.customize));
    Shop.set('discount', Number(req.params.discount));
    Shop.set('describe', req.params.describe);
    Shop.set('stock', Number(req.params.stock));
    var models = JSON.parse(req.params.model);
    var modelArray = await functionTool.saveModelForUpdateGoods(objectId, models);
    Shop.set("modelArray", modelArray);
    let goodsTypeOId = req.body.goodsTypeOId
    if (goodsTypeOId != "" && goodsTypeOId != undefined && goodsTypeOId != null) {
        var shop_good_type_Obj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
        Shop.set('shop_good_type_OId', goodsTypeOId);
        Shop.set('shop_good_type_Obj', shop_good_type_Obj);
    }
    // 保存到云端
    Shop.save().then(function (goods) {
            return res.send("1")
        }, function (error) {
            console.log(error);
            return res.send("2")
        }
    )
})
router.post('/goodsMangerTree', function (req, res) {
    functionTool.goodsType(function (result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/userLevelTree', function (req, res) {

    functionTool.levelType('', '', '', function (result, resultTree) {
        res.send(JSON.stringify(result));

    })
});

router.post('/userLevelInformation', function (req, res) {
    var id = req.body.dept_id;
    var name = req.body.name;
    var objectId = req.body.objectId;
    if (id == "" || id == undefined || id == null) {
        id = '0';
    }
    functionTool.levelType(id, name, objectId, function (result, resultTree) {
        res.send(JSON.stringify(resultTree));
    })
});

router.get('/addLevelTree', function (req, res, next) {
    var levelName = req.query.levelName;
    var obj = {};
    obj.levelName = levelName;
    functionTool.levelTypeInformation(function (result, resultTree) {
        obj.result = JSON.stringify(result);
        res.render('level/addLevelTree', {result: obj});
    })

});

router.post('/addUserLevelTree', function (req, res, next) {
    req.params = req.body;
    functionTool.addUserLevel(req, function (result) {
        res.send();
    })
});

router.post('/regUserDefault', async function (req, res) {
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await functionTool.getRegUserDefault(page, num);
    res.send(JSON.stringify(result));
})

router.get('/regUserAdd', function (req, res) {
    res.render('reg/regUserSelect')
})

router.post('/userFind', async function (req, res) {
    let name = req.body.name;
    let objectId = req.body.objectId;
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await functionTool.getUserMember(name, objectId, page, num);
    res.send(JSON.stringify(result));
})

router.post('/findRegUser', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.findUserMember(objectId);
    res.send(JSON.stringify(result));
})

router.post('/insertRegUserDefault', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.insertRegUserDefault(objectId);
    res.send(JSON.stringify(result));
})

router.post('/regUserRemove', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.regUserRemove(objectId);
    res.send(JSON.stringify(result));
})

router.post('/userLevelManger', function (req, res) {
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var name = req.body.name;
    var levelOId = req.body.dept_id;
    var weChat = req.body.weChat;
    var idCard = req.body.idCard;
    var authCode = req.body.authCode;
    var status = req.body.status;
    functionTool.userLevelInformation(objectId, name, levelOId, weChat, idCard, authCode, status, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});


router.get('/userAdd', function (req, res) {
    functionTool.levelTypeInformation(function (result, resultTree) {
        res.render("authorization/addUser", {result: JSON.stringify(resultTree)});
    })
});

// router.post('/addUserInformation', function(req, res, next) {
//     var authCode = randomWord(true,6,6);
//     add(authCode);
//     function add(authCode) {
//         var query = new AV.Query('Authorization_certificate');
//         query.equalTo("authCode",authCode);
//         query.count().then(function (count) {
//                 if (count>0){
//                     var newAuthCode = randomWord(true,6,6);
//                     add(newAuthCode);
//                 }else {
//                     req.body.authCode = authCode;
//                     req.params = req.body;
//                     functionTool.addUserLevelInformation(req,function (user) {
//                         functionTool.findUserLevel(user.id,function (error,result) {
//                             var filePath = path+'/public/image/newAuth.png';
//                             var chapterPath = path+'/public/image/chapter.png';
//                             var key = uuid.v1().replace(/-/g, "")+".png";
//                             var imagePath =  path+key;
//                             imageMagick(filePath)
//                                 .font(path+'/public/font/lantinhj.ttf')
//                                 .fontSize(21)
//                                 .fill('#222222')
//                                 .drawText(315, 406, result.authCode)
//                                 .drawText(210, 502, result.name)
//                                 .drawText(232, 543, result.idCard)
//                                 .drawText(208, 586, result.weChat)
//                                 .drawText(208, 626, result.telephone)
//                                 .drawText(232, 996, result.levelName)
//                                 .drawText(186, 1038,result.teamLeader)
//                                 .drawText(236, 1120, result.resultTime)
//                                 .write(imagePath, function (err) {
//                                     if (!err) {
//                                         imageMagick()
//                                             .in('-page', '+0+0')
//                                             .in(imagePath)
//                                             .in('-page', '+468+1070') // location of smallIcon.jpg is x,y -> 10, 20
//                                             .in(chapterPath)
//                                             .mosaic()
//                                             .write(imagePath, function (err) {
//                                                 if (!err)
//                                                 {
//                                                     qn.uploadImg(imagePath,key,function (error,rs) {
//                                                         if (rs=='200'){
//                                                             functionTool.updateUserAuthImage(user.id,key,function (error,rs) {
//                                                                 res.send("10000");
//                                                                 fs.unlinkSync(imagePath);
//                                                             });
//                                                         }else{
//                                                             res.send("10002");
//                                                         }
//                                                     })
//                                                 }
//                                                 else {
//                                                     console.log(err)
//                                                 };
//                                             });
//                                     } else {
//                                         console.log(err.message || "出错了！");
//                                     }
//                                 });
//                         })
//                     })
//                 }
//             }
//         )
//     }
// });

router.post('/addUserInformation', function (req, res, next) {
    var authCode = randomWord(true, 6, 6);
    add(authCode);
    function add(authCode) {
        var query = new AV.Query('Authorization_certificate');
        query.equalTo("authCode", authCode);
        query.count().then(function (count) {
                if (count > 0) {
                    add(newAuthCode);
                } else {
                    req.body.authCode = authCode;
                    req.params = req.body;
                    functionTool.addUserLevelInformation(req, function (user) {
                        functionTool.findUserLevel(user.id, function (error, result) {
                            var authClass = 'taiZiFei';
                            var authImg = new functionTool.AuthImg(result, authClass)
                            authImg.upload(function (err, img) {
                                if (!err) {
                                    res.send(img)
                                } else {
                                    console.log(img)
                                    res.send(img)
                                }
                            })
                        })
                    })
                }
            }
        )
    }
});

// router.post('/editUserInformation', function(req, res, next) {
//     req.params = req.body;
//     functionTool.addUserLevelInformation(req,function (user) {
//         functionTool.findUserLevel(user.id,function (error,result) {
//             var filePath = path+'/public/image/newAuth.png';
//             var chapterPath = path+'/public/image/chapter.png';
//             var key = uuid.v1().replace(/-/g, "")+".png";
//             var imagePath =  path+key;
//             imageMagick(filePath)
//             .font(path+'/public/font/lantinhj.ttf')
//             .fontSize(21)
//             .fill('#222222')
//             .drawText(315, 406, result.authCode)
//             .drawText(210, 502, result.name)
//             .drawText(232, 543, result.idCard)
//             .drawText(208, 586, result.weChat)
//             .drawText(208, 626, result.telephone)
//             .drawText(232, 996, result.levelName)
//             .drawText(186, 1038,result.teamLeader)
//             .drawText(236, 1120, result.resultTime)
//             .write(imagePath, function (err) {
//                 if (!err) {
//                     imageMagick()
//                         .in('-page', '+0+0')
//                         .in(imagePath)
//                         .in('-page', '+468+1070') // location of smallIcon.jpg is x,y -> 10, 20
//                         .in(chapterPath)
//                         .mosaic()
//                         .write(imagePath, function (err) {
//                             if (!err)
//                             {
//                                 qn.uploadImg(imagePath,key,function (error,rs) {
//                                     if (rs=='200'){
//                                         functionTool.updateUserAuthImage(user.id,key,function (error,rs) {
//                                             res.send("10000");
//                                             fs.unlinkSync(imagePath);
//                                         });
//                                     }else{
//                                         res.send("10002");
//                                     }
//                                 })
//                             }
//                             else {
//                                 console.log(err)
//                             };
//                         });
//                 } else {
//                     console.log(err.message || "出错了！");
//                 }
//             });
//         })
//     })
// });
router.post('/editUserInformation', function (req, res, next) {
    req.params = req.body;
    functionTool.addUserLevelInformation(req, function (user) {
        functionTool.findUserLevel(user.id, function (error, result) {
            var authClass = 'taiZiFei';
            var authImg = new functionTool.AuthImg(result, authClass)
            authImg.upload(function (err, img) {
                if (!err) {
                    res.send(img)
                } else {
                    console.log(img)
                    res.send(img)
                }
            })
        })
    })
});

router.get('/userLevelEdit', function (req, res) {
    var id = req.query.id;
    functionTool.userLevelInformation(id, '', '', '', '', '', '', '', '', function (err, result) {
        functionTool.levelTypeInformation(function (rs, resultTree) {
            result.levelTree = JSON.stringify(resultTree);
            res.render("authorization/editUser", {result: result})
        })
    });
});
router.get('/levelEdit', function (req, res, next) {
    var levelName = req.query.levelName;
    var name = req.query.name;
    var id = req.query.id;
    var obj = {};
    obj.levelName = levelName;
    obj.name = name;
    obj.id = id;
    functionTool.levelTypeInformation(function (result, resultTree) {
        obj.result = JSON.stringify(result);
        res.render('level/levelEdit', {result: obj});
    })

});
router.post('/levelTree', function (req, res, next) {
    functionTool.levelTypeInformation(function (result, resultTree) {
        res.send(JSON.stringify(result));
    })
});

router.post('/levelRemove', function (req, res, next) {
    var id = req.body.id;
    functionTool.levelRemove(id, function (result) {
        res.send(result);
    })
});
router.post('/userLevelAuth', async function (req, res, next) {
    var objectIds = req.body.objectId;
    objectIds = objectIds.split("-");
    var arrLen = objectIds.length;
    while (objectIds.length > 0) {
        let objectId = objectIds.shift()
        await functionTool.findUserLevel(objectId, function (error, result) {
            var authClass = 'taiZiFei';
            var authImg = new functionTool.AuthImg(result, authClass)
            authImg.upload(function (err, img) {
                if (!err) {
                    arrLen--;
                    if (arrLen <= 0) {
                        res.send("10000");
                    }
                    res.send(img)
                } else {
                    console.log(img)
                    objectIds.push(objectId);
                }
            })
        })
    }

});


router.post('/lookAuthCode', function (req, res) {
    var key = req.body.key;
    functionTool.findAuthImage(key, function (error, result) {
        if (error == 'null') {
            var imagePath = "http://tribemedia.aladada.com/" + result.authImage;
            return res.render("auth/authImage", {result: imagePath});
        } else {
            return res.render("auth/notFind", {});
        }

    })
});


router.post("/login", function (req, res) {
    var username = req.body.username;
    var password = req.body.password;
  AV.User.logIn(username, password).then(function (user) {
        let query = new AV.Query("Admin_user")
        query.equalTo("userOId", user.id);
        query.equalTo("status", 1);
        query.first().then((result) => {
            if (result != "" && result != null) {
                res.saveCurrentUser(user);
                res.send();
            } else {
                res.send("0")
            }
        })
    }, function (error) {
        console.log(error)
        res.send('0')
    });
});

router.post("/shopOrder", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var status = req.body.status;
    var receiver = req.body.receiver;
    var orderCode = req.body.orderCode;
    var shopName = req.body.shopName;
    var buyerUser = req.body.buyerUser;
    var buyerOId = req.body.buyerOId;
    functionTool.shopOrderList('', '', status, receiver, orderCode, shopName, buyerUser, buyerOId, page, num, function (error, result) {
        if (!error) {
            res.send(JSON.stringify(result));
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.get("/shopOrderInfo", function (req, res) {
    var page = req.query.pageIndex;
    page = Number(page) + 1;
    var num = req.query.pageSize;
    var objectId = req.query.objectId;
    var orderCode = req.query.orderCode;
    var resultArr = {};
    functionTool.shopOrderList(objectId, '', '', '', orderCode, '', '', '', page, num, function (error, result) {
        functionTool.shopOrderLog(objectId, function (err, logObj) {
            resultArr.result = result;
            resultArr.logObj = logObj;
            res.send(JSON.stringify(resultArr));
        })

    });
});

router.post("/updateOrder/buyer", function (req, res) {
    req.body = JSON.parse(req.body.data);
    req.params = req.body;
    functionTool.updataOrderStatus(req, function (err, result) {
        res.send();
    })
});

router.get("/updateOrder/refund", function (req, res) {
    var id = req.query.id;
    functionTool.shopOrderRefund(id, function (err, result) {
        res.render('order/orderRefund', {result: result})
    })
});
router.post("/updateOrder/updateStatus", function (req, res) {
    req.params = req.body;
    functionTool.updataOrderStatus(req, function (err, result) {
        res.send(result);
    })
});

// 退款逻辑
router.post('/doWxRefund', function (req, res) {
    // var returnResult = {};
    // var state = 0;
    // var msg = "";
    // var currentUser = req.currentUser;
    // if (currentUser == null) {
    //     returnResult["state"] = state;
    //     returnResult["msg"] = "无权进入";
    //     return res.send(JSON.stringify(returnResult));
    // } else {
    //     var err = null;
    //     var orderNo = req.body.orderNo;
    //     var uId = currentUser.id;
    //     if (orderNo == "" || orderNo == null || orderNo == undefined) {
    //         result["state"] = state;
    //         result["msg"] = "错误的参数";
    //         return res.send(JSON.stringify(returnResult));
    //     } else {
    //         orderNo = parseInt(orderNo);
    //         var orderQuery = new AV.Query('Shop_order');
    //         orderQuery.equalTo("orderCode", orderNo);
    //         orderQuery.include("orderRefundObj");
    //         orderQuery.include("payInfo");
    //         orderQuery.include("orderGoodsArray");
    //         orderQuery.first().then(function (orderObj) {
    //             if (orderObj == null) {
    //                 returnResult["state"] = state;
    //                 returnResult["msg"] = "未查询到有效数据";
    //                 return res.send(JSON.stringify(returnResult));
    //             } else {
    //                 //拼接退款参数(默认1240018502商户)
    //                 var sellerNo = orderObj.get("payInfo").get("sellerNo");
    //                 var params = {};
    //                 params["mch_id"] = sellerNo,
    //                     params["transaction_id"] = orderObj.get("payInfo").get("tradeNo"),
    //                     params["out_trade_no"] = orderObj.get("orderCode").toString(),
    //                     params["total_fee"] = common.formatMoney(orderObj.get("totalPrice") * 100);//强制处理小数防止产生浮点数,
    //                 params["refund_fee"] = common.formatMoney(orderObj.get("orderRefundObj").get("refundFee") * 100);//强制处理小数防止产生浮点数,
    //                 params["appid"] = apis['wxConfig']['appid'],
    //                     params["partner_key"] = apis['wxConfig']['partner_key2'];
    //                 if (sellerNo == "1269577001") {
    //                     //params["appid"] = apis['wxConfig']['appID'];
    //                     params["partner_key"] = apis['wxConfig']['partner_key'];
    //                     params["pfx"] = fs.readFileSync('cloud/apiclient_cert_77001.p12');
    //                 } else {
    //                     params["pfx"] = fs.readFileSync('cloud/apiclient_cert_18502.p12');
    //                 }
    //                 params["out_refund_no"] = new Date().getTime().toString() + (Math.random() * 900000 + 100000).toFixed(0);
    //                 params["op_user_id"] = req.AV.user.id;
    //                 params["refund_account"] = "REFUND_SOURCE_RECHARGE_FUNDS";
    //
    //
    //                 console.log("退款金额：" + params["refund_fee"] + "订单总金额：" + params["total_fee"]);
    //
    //
    //                 var wxpay = WXPay(params);
    //                 //发起退款
    //                 wxpay.orderRefund(params, function (err, result) {
    //
    //
    //                     res.setHeader('content-type', 'text/html;charset=utf-8');
    //                     if (err) {
    //                         returnResult["state"] = state;
    //                         returnResult["msg"] = err;
    //                         return res.send(JSON.stringify(returnResult));
    //                     } else {
    //                         console.log("退款通知：" + JSON.stringify(result));
    //                         if (result.return_code == "SUCCESS" && result.result_code == "SUCCESS") {
    //                             var refundObj = {};
    //                             refundObj["fee"] = common.formatMoney(parseFloat(result.refund_fee) / 100);
    //                             refundObj["type"] = ["微信支付"];
    //                             refundObj["tradeNo"] = orderObj.get("payInfo").get("tradeNo");
    //                             doOrderRefund(orderObj, refundObj, function (error, msg) {
    //                                 console.log(msg);
    //                                 if (error == null) {
    //                                     state = 1;
    //                                 }
    //                                 returnResult["state"] = state;
    //                                 returnResult["msg"] = error;
    //                                 return res.send(JSON.stringify(returnResult));
    //                             })
    //                         } else if (result.return_code == "NOTENOUGH") {
    //                             returnResult["state"] = state;
    //                             returnResult["msg"] = "请求退款错误：" + result.err_code_des + "。错误代码：" + result.err_code;
    //                             return res.send(JSON.stringify(returnResult));
    //                         } else if (result.result_code == "FAIL") {
    //                             state = 2;
    //                             returnResult["state"] = state;
    //                             returnResult["msg"] = "请求退款错误：" + result.err_code_des + "。错误代码：" + result.err_code;
    //                             return res.send(JSON.stringify(returnResult));
    //                         }
    //                     }
    //
    //
    //                 });
    //             }
    //         }, function (error) {
    //             returnResult["state"] = state;
    //             returnResult["msg"] = error.message;
    //             return res.send(JSON.stringify(returnResult));
    //         })
    //     }
    // }
});
//执行退款后的逻辑
function doOrderRefund(orderObj, refundObj, callback) {
    var fee = refundObj["fee"];
    if (isNaN(fee))
        fee = 0.01;
    orderObj.set("oldStatus", orderObj.get("status"));
    var refundRate = common.formatMoney((orderObj.get("totalPrice") - fee) / orderObj.get("totalPrice"));
    if (common.formatMoney(orderObj.get("totalPrice") - fee) != 0) {
        orderObj.set("sellerFee", common.formatMoney(orderObj.get("totalPrice") - fee));
        orderObj.set("sysAuditAccountStatus", apis["auditAccountStatus"]["auditWait"]);//待审核
        orderObj.set("promote", 0);
    } else {
        orderObj.set("promote", 1);
        orderObj.set("sellerFee", 0);
    }
    orderObj.set("status", apis["order"]["status_refundOk"]);//完成
    orderObj.set("promoterFee", 0);
    orderObj.set("distributionFee", 0);
    orderObj.set("refundOkFee", fee);//退款金额
    orderObj.set("task", null);//清除定时任务
    orderObj.set("taskTime", null);
    orderObj.save().then(
        function (newOrderObj) {
            //删除订单明细里除卖家外的返利
            var orderGoodsObjs = orderObj.get("orderGoodsArray");
            for (var i = 0; i < orderGoodsObjs.length; i++) {
                orderGoodsObjs[i].set("promoterFee", 0);
                orderGoodsObjs[i].set("distributionFee", 0);
                orderGoodsObjs[i].set("writerFee", 0);
                orderGoodsObjs[i].set("sellerFee", common.formatMoney(orderGoodsObjs[i].get("price") * orderGoodsObjs[i].get("num") * refundRate));
            }
            AV.Object.saveAll(orderGoodsObjs).then(
                function (error) {
                    if (error != null) {
                        //保存退款明细

                        var orderRefundMap = {};
                        orderRefundMap["title"] = "退款成功";
                        orderRefundMap["content"] = "";
                        orderRefundMap["uId"] = "";
                        orderRefundMap["orderOId"] = newOrderObj.id;
                        orderRefundMap["pics"] = [];
                        orderRefundMap["refundFee"] = common.formatMoney(fee);
                        orderRefundMap["type"] = "3";
                        addOrderRefundDetail(orderRefundMap, function (err, orderRefundObj) {
                        });
                        var toUserOId = orderObj.get("buyerOId");
                        // 推送交易消息
                        var msg_content = {};
                        msg_content["content"] = "你的订单：" + newOrderObj.get("orderCode") + "，已退款(" + fee + "元)成功，请到" + refundObj['type'] + "(交易号" + refundObj["tradeNo"] + ")进行查看。";
                        console.log("ddd");
                        var msg_extra = {};
                        msg_extra["extra"] = apis['message_profession_code']['transaction_code']; //交易消息代码
                        msg_extra["code"] = apis['message_type_code']['word']; //文本消息
                        msg_extra["content"] = msg_content;

                        var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
                        base64Content = base64Content.replace(/\+/g, "@");
                        base64Content = base64Content.replace(/\=/g, "");
                        var sendObj = {};
                        sendObj["operation"] = "";
                        sendObj["sourceUserId"] = "";
                        sendObj["targetUserId"] = "";
                        sendObj["extra"] = base64Content;
                        message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
                        });
                        //记录到系统消息中
                        var SystemMessage = AV.Object.extend('SystemMessage');
                        var systemMessage = new SystemMessage();
                        systemMessage.set('targetUserOId', toUserOId);
                        systemMessage.set('targetUserObj', {
                            "__type": "Pointer",
                            className: "_User",
                            objectId: toUserOId
                        });
                        systemMessage.set('sortTime', common.getCurrTime());
                        systemMessage.set('status', 0);
                        systemMessage.set('messageType', 2);
                        systemMessage.set('isBuyer', 1);
                        systemMessage.set('orderObj', newOrderObj);
                        systemMessage.set('title', '退款成功');
                        systemMessage.set('content', msg_content['content']);
                        systemMessage.save();
                        return callback(null, "success");
                    } else {
                        return callback(error, null);
                    }
                })
        },
        function (errorObj, error) {
            return callback(error.message, null);
        }
    )
}
function addOrderRefundDetail(orderRefundMap, cb) {
    if (orderRefundMap == null || orderRefundMap == "" || orderRefundMap == undefined)
        return cb("无效的对象", null);
    var Shop_order_refund = AV.Object.extend("Shop_order_refund");
    var orderRefundObj = new Shop_order_refund();
    orderRefundObj.set("title", orderRefundMap["title"]);
    if (orderRefundMap["contentCode"] != null && orderRefundMap["contentCode"] != undefined) {
        orderRefundObj.set("refundReasonCode", orderRefundMap["contentCode"]);
    }
    orderRefundObj.set("refundReason", orderRefundMap["content"]);
    if (orderRefundMap["refundFee"] != null && orderRefundMap["refundFee"] != "" && orderRefundMap["refundFee"] != undefined)
        orderRefundObj.set("refundFee", orderRefundMap["refundFee"]);
    if (orderRefundMap["uId"] != "") {
        orderRefundObj.set("refunder", orderRefundMap["uId"]);
        orderRefundObj.set("refundObj", {"__type": "Pointer", className: "_User", objectId: orderRefundMap["uId"]});
    }
    orderRefundObj.set("orderOId", orderRefundMap["orderOId"]);
    orderRefundObj.set("orderObj", {
        "__type": "Pointer",
        className: "Shop_order",
        objectId: orderRefundMap["orderOId"]
    });
    orderRefundObj.set("type", orderRefundMap["type"]);
    //保存上传凭证
    saveOrderRefundPics(orderRefundMap["pics"], function (err, picList) {
        if (err) {
            return cb(err, null);
        } else {
            orderRefundObj.set("picArray", picList);
            orderRefundObj.save().then(function (newOrderRefundObj) {
                return cb(null, newOrderRefundObj);
            }, function (errObj, err) {
                return cb(err.message, null);
            });
        }
    });
}
// 保存订单退款凭证
function saveOrderRefundPics(pics, cb) {
    if (pics.length == 0)
        return cb(null, pics);
    var shopCommonPicsArry = [];
    var picIds = [];
    for (var i = 0; i < pics.length; i++) {
        picIds.push(pics[i]["objectId"]);
    }
    //先查询旧的凭证
    var query = new AV.Query('Shop_common_pic');
    query.containedIn("picName", picIds);
    query.find({
        success: function (picObjs) {
            var picMap = {};
            for (var i = 0; i < picObjs.length; i++) {
                picObjs[i].set("sortNum", i + 1);
                picMap[picObjs[i].get("picName")] = picObjs[i];
            }
            var ShopCommonPic = common.getEntity("Shop_common_pic");
            for (var i = 0; i < picIds.length; i++) {
                if (picMap[picIds[i]] == null) {
                    var shopcommonPic = new ShopCommonPic();
                    shopcommonPic.set("picName", picIds[i]);
                    shopcommonPic.set("sortNum", i + 1);
                    shopCommonPicsArry.push(shopcommonPic);
                }
            }
            AV.Object.saveAll(shopCommonPicsArry, function (list, error) {
                for (var i = 0; i < picObjs.length; i++) {
                    list.push(picObjs[i]);
                }
                list.sort(function (a, b) {
                    return b.get("sortNum") - a.get("sortNum")
                });
                return cb(null, list);
            });
        }, error: function (err) {
            return cb(err, null);
        }
    })
}
// 拒绝退款逻辑
router.post('/sysOrderRefundRefuse', function (req, res) {
    var result = {};
    var state = 0;
    var msg = "";
    var currentUser = req.currentUser;
    if (currentUser == null) {
        result["state"] = state;
        result["msg"] = "无权操作！";
        return res.send(JSON.stringify(result));
    } else {
        var maxLength = 1000;
        var orderNoArry = req.body.orderNo;//订单号
        if (typeof orderNoArry == "string")
            orderNoArry = [orderNoArry];
        orderNoArry = common.arrayDistinctStr(orderNoArry);
        if (orderNoArry.length > maxLength || orderNoArry.length == 0) {
            result["state"] = state;
            result["msg"] = "最多选择1000条数据！";
            return res.send(JSON.stringify(result));
        } else {
            for (var i = 0; i < orderNoArry.length; i++) {
                orderNoArry[i] = parseInt(orderNoArry[i]);
            }
            //查询订单
            var orderQuery = new AV.Query('Shop_order');
            orderQuery.containedIn("orderCode", orderNoArry);
            orderQuery.include("orderRefundObj");
            orderQuery.limit(maxLength);
            orderQuery.find().then(function (orderObjs) {
                    var title = "";
                    var sendContent = "";
                    async.eachSeries(orderObjs, function (orderObj, callback) {
                        title = "系统拒绝退款";
                        orderObj.set("oldStatus", orderObj.get("status"));
                        orderObj.set("status", orderObj.get("refundStatus"));
                        orderObj.set("task", orderObj.get("refundTask"));
                        orderObj.set("taskTime", orderObj.get("refundTaskTime"));
                        sendContent = "系统拒绝了订单" + orderObj.get("orderCode") + "的退款申请";
                        //保存退款明细
                        var orderRefundMap = {};
                        orderRefundMap["title"] = title;
                        orderRefundMap["content"] = "";
                        orderRefundMap["uId"] = "";
                        orderRefundMap["orderOId"] = orderObj.id;
                        orderRefundMap["pics"] = [];
                        if (orderObj.get("orderRefundObj") != null && orderObj.get("orderRefundObj") != "")
                            orderRefundMap["refundFee"] = common.formatMoney(orderObj.get("orderRefundObj").get("refundFee"));
                        orderRefundMap["type"] = "3";
                        addOrderRefundDetail(orderRefundMap, function (err, orderRefundObj) {
                            if (err != null) {
                                callback(err);
                            } else {

                                orderObj.save().then(function (newOrderObj) {
                                        state = 1;
                                        result["state"] = state;
                                        result["msg"] = err;
                                        return res.send(JSON.stringify(result));
                                        var toUserOId = orderObj.get("buyerOId");
                                        // 推送交易消息
                                        var msg_content = {};
                                        msg_content["content"] = sendContent;

                                        var msg_extra = {};
                                        msg_extra["extra"] = apis['message_profession_code']['transaction_code']; //交易消息代码
                                        msg_extra["code"] = apis['message_type_code']['word']; //文本消息
                                        msg_extra["content"] = msg_content;

                                        var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
                                        base64Content = base64Content.replace(/\+/g, "@");
                                        base64Content = base64Content.replace(/\=/g, "");

                                        var sendObj = {};
                                        sendObj["operation"] = "";
                                        sendObj["sourceUserId"] = "";
                                        sendObj["targetUserId"] = "";
                                        sendObj["extra"] = base64Content;
                                        message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
                                        });

                                        //记录到系统消息中
                                        var SystemMessage = common.getEntity('SystemMessage');
                                        var systemMessage = new SystemMessage();
                                        systemMessage.set('targetUserOId', toUserOId);
                                        systemMessage.set('targetUserObj', {
                                            "__type": "Pointer",
                                            className: "_User",
                                            objectId: toUserOId
                                        });
                                        systemMessage.set('sortTime', common.getCurrTime());
                                        systemMessage.set('status', 0);
                                        systemMessage.set('messageType', 2);
                                        systemMessage.set('isBuyer', 1);
                                        systemMessage.set('orderObj', newOrderObj);
                                        systemMessage.set('title', title);
                                        systemMessage.set('content', msg_content['content']);
                                        systemMessage.save();

                                        callback(null);
                                    },
                                    function (errObj, err) {
                                        callback(err.message);
                                    }
                                );
                            }

                        })
                    }, function (err) {
                        if (err == null)
                            state = 1;
                        result["state"] = state;
                        result["msg"] = err;
                        return res.send(JSON.stringify(result));
                    });
                }, function (err) {
                    result["state"] = state;
                    result["msg"] = err.message;
                    return res.send(JSON.stringify(result));
                }
            )
        }
    }
});
router.post("/updateOrder/sendGoods", function (req, res) {
    req.params = req.body;
    functionTool.doSendGoods(req, function (err, result) {

        res.send(JSON.stringify(result));
    })
});

router.get("/updateOrder/send", function (req, res) {
    var objectId = req.query.id
    functionTool.shopOrderList(objectId, '', '', '', '', '', '', '', '', '', function (error, result) {
        res.render('order/orderSend', {result: result});
    });
});


router.post("/liveManger", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var tribeOId = req.body.tribeOId;
    var qiniuStreamId = req.body.qiniuStreamId;
    var createrOId = req.body.createrOId;
    var nickName = req.body.nickName;
    functionTool.liveList('', tribeOId, qiniuStreamId, createrOId, nickName, page, num, function (error, result) {
        if (!error) {
            res.send(JSON.stringify(result));
        } else {
            res.send(result);
        }
    })
});
//部落直播管理
router.post("/tribeManger", async function (req, res) {
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let tribeOId = req.body.tribeOId;
    let qiniuStreamId = req.body.qiniuStreamId;
    let createrOId = req.body.createrOId;
    let nickName = req.body.nickName;
    let result = await functionTool.tribeLiveList('', tribeOId, qiniuStreamId, createrOId, nickName, page, num);
    res.send(JSON.stringify(result));
});


router.get("/liveBack", function (req, res) {
    var resultObj = {};
    var streambackup = req.query.streambackup;
    var objectId = req.query.objectId;
    var status = req.query.status;
    var isRecord = req.query.isRecord;
    resultObj.streambackup = streambackup;
    resultObj.objectId = objectId;
    resultObj.status = status;
    resultObj.isRecord = isRecord;
    res.render('live/livePlayer', {result: resultObj})
});
router.post("/createLiveForDevice", function (req, res) {
    let params = req.body;
    // console.log(params,'---')
    functionTool.createLive(params, function (error, result) {
        // console.log(result)
        // console.log(error)
        if (error == null && result) {
            res.send('1');
        } else {
            res.send('0');
        }
    });
});
router.post("/updateLive", function (req, res) {
    req.params = req.body;
    functionTool.updateLive(req, function (error, result) {
        if (!error) {
            res.send("1");
        } else {
            res.send("0");
        }
    });
});
router.post("/removeLive", function (req, res) {
    req.params = req.body;
    functionTool.removeLive(req, function (error, result) {
        if (error == null) {
            res.send("1");
        } else {
            res.send("0");
        }
    });
});
router.post("/updateLiveRoom", async function (req, res) {
    req.params = req.body;
    let result = await functionTool.updateLiveRoom(req);
    if (result) {
        res.send("1");
    } else {
        res.send("0");
    }
});

router.get("/liveEdit", function (req, res) {
    var objectId = req.query.objectId;
    functionTool.liveList(objectId, '', '', '', '', '', '', function (error, result) {
        res.render('live/liveEdit', {result: result});
    })
});

router.get("/liveCopy", function (req, res) {
    var liveObjectId = req.query.objectId;
    res.render('live/tribeList', {liveObjectId: liveObjectId});
})
router.post("/liveCopy", async function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var name = req.body.name;
    let result = await functionTool.tribeList(page, num, name);
    res.send(JSON.stringify(result));
})

router.post('/addTribeLive', async function (req, res) {

    req.params = req.body;
    let result = await functionTool.saveTribeLive(req);
    if (result) {
        res.send("1")
    }
})

router.get("/liveAdd", function (req, res) {
    //视频token
    var config = qn.liveConfig;

    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0
        // persistentOps:'avthumb/m3u8/noDomain/1/segtime/15/vb/400k',
        // persistentNotifyUrl:'http://exmanager.leanapp.cn/qiniuCallBack/liveCallBackNotify',
        // persistentPipeline: "duilie1",
        // callbackBody : '{"uploadType":3,"key": $(key),"mimeType": $(mimeType),"ext": $(ext),"name": $(fname),"size": $(fsize),"hash": $(etag),"avinfo": $(avinfo),"imageInfo":$(imageInfo)}',
        // callbackBodyType:"application/json",
        // saveKey:`${uuid.v4()}.m3u8`
    };

    // let options = {
    //     scope: config.Bucket,
    //     deadline:Date.now()/1000+3600,
    //     persistentOps:"avthumb/mp4/vb/640k;vframe/jpg/offset/0.001/;avthumb/m3u8/segtime/5/preset/video_640k/rotate/90",
    //     persistentNotifyUrl:"http://zhixingli.aladada.com/qiniuPersistentMediaSuccess",
    //     persistentPipeline : "duilie1"
    // };

    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    //封面图token
    var token = putPolicy.uploadToken(mac);
    var configPic = qn.config;
    var optionsPic = {
        scope: configPic.Bucket,
        deleteAfterDays: 0,
    }
    var putPolicyPic = new qiniu.rs.PutPolicy(optionsPic);
    var macPic = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var tokePic = putPolicyPic.uploadToken(macPic);
    console.log(token)
    console.log(tokePic)
    res.render('live/liveAdd', {
        domain: config.Domain,
        uptoken: token,
        uptokenPic: tokePic,
    });
});

// router.post("/getQiniuToken1", function (req, res) {
//   var config = qn.liveConfig;
//   var options = {
//     scope: config.Bucket,
//     deleteAfterDays: 0
//   };
//   let mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
//   let requestURI = ' http://pili.qiniuapi.com/v2/hubs/buluoquan/streams'
//   let reqMethod = 'GET'
//   let reqContentType = 'application/x-www-form-urlencoded'
//   let reqBody = ''
//   let token = qiniu1.util.generateAccessTokenV2(mac,requestURI,reqMethod,reqContentType,null)
//   console.log(token)
//   res.send()
// })
router.get("/deviceLiveAdd", function (req, res) {
    //token
    var config = qn.liveConfig;

    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    //封面图token
    var token = putPolicy.uploadToken(mac);
    var configPic = qn.config;
    var optionsPic = {
        scope: configPic.Bucket,
        deleteAfterDays: 0,
    }
    var putPolicyPic = new qiniu.rs.PutPolicy(optionsPic);
    var macPic = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var tokePic = putPolicyPic.uploadToken(macPic);
    res.render('live/deviceLiveAdd', {
        domain: config.Domain,
        uptoken: token,
        uptokenPic: tokePic,
    });
});
//收入列表
router.post("/accountOrder", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var remark = req.body.remark;
    var nickName = req.body.nickName;
    var userOId = req.body.userOId;
    functionTool.accountList(remark, userOId, nickName, page, num, function (error, result) {
        res.send(JSON.stringify(result))
    })
});

router.get("/getIncomSource", function (req, res) {

    var objectId = req.query.objectId;
    var userOId = req.query.userOId;
    var type = req.query.type;
    functionTool.getIncomeDetail(userOId, objectId, type, function (err, result) {
        if (!err) {
            res.send(result);
        } else {
            console.log(err);
        }
    })
});

router.post("/whereMoney", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var remark = req.body.remark;
    var nickName = req.body.nickName;
    var userOId = req.body.userOId;
    functionTool.accountList(remark, userOId, nickName, page, num, function (error, result) {
        res.send(JSON.stringify(result))
    })
});

router.get("/money/whereDetail", function (req, res) {
    var orderNo = req.query.orderNo;
    functionTool.moneyWhereDetail(orderNo, function (error, result) {
        if (error) {
            console.log(error);
            res.send();
        } else {
            res.send(JSON.stringify(result))
        }
    })
});
//生成XX-XXXX图片授权码
function randomWord(randomFlag, min, max) {
    var str = "",
        range = min,
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var arrTwo = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    // 随机产生
    str += arrTwo[Math.round(Math.random() * (arrTwo.length - 1))] + arrTwo[Math.round(Math.random() * (arrTwo.length - 1))] + "-";
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        var pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos]
    }
    return str;
}

router.post("/tribalCreateUser", function (req, res) {

    // var page = Number(req.body.page)+1;
    // var num = req.body.name;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;

    var userOId = req.body.userOId;
    var nickName = req.body.nickName;
    functionTool.allowCreateTribeList(userOId, nickName, page, num, function (error, result) {
        res.send(JSON.stringify(result))
    })
});

router.post("/allow/createTribe", function (req, res) {
    var userOId = req.body.userOId;
    var status = req.body.status;
    functionTool.allowCreateTribeUser(userOId, status, function (err, result) {
        if (!err) {
            if (result == 2) {
                res.send("2")
            } else {
                res.send("1");
            }
        } else {
            res.send("0");
        }
    })
});

router.post("/moneyWhere", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var receiver = req.body.receiver;
    var orderCode = req.body.orderCode;
    var shopName = req.body.shopName;
    var buyerUser = req.body.buyerUser;
    var buyerOId = req.body.buyerOId;
    functionTool.moneyWhere('', '', receiver, orderCode, shopName, buyerUser, buyerOId, page, num, function (error, result) {
        if (!error) {
            res.send(JSON.stringify(result));
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.post("/userMergeManger", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var saveUserOId = req.body.saveUserOId;
    var saveUserName = req.body.saveUserName;
    var delUserName = req.body.delUserName;
    var delUserOId = req.body.delUserOId;
    functionTool.userMergedList(saveUserOId, saveUserName, delUserOId, delUserName, page, num, function (error, result) {
        if (!error) {
            res.send(JSON.stringify(result));
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.post("/suggestionList", function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var phoneNum = req.body.phoneNum;
    var type = req.body.type;
    var status = req.body.status;
    functionTool.suggestionList(phoneNum, type, status, page, num, function (error, result) {
        if (!error) {
            res.send(JSON.stringify(result));
        } else {
            res.send(JSON.stringify(result));
        }
    })
});

router.post("/suggestion/status", function (req, res) {
    req.params = req.body;
    functionTool.updateSuggestion(req, function (err, result) {
        if (err) {
            res.send("0")
        } else {
            res.send("1");
        }
    })
});

router.post('/relateGoodsInformation', function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var objectId = req.body.objectId.split("-");
    functionTool.relateGoodsInformation(objectId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/relate/tribeGoodsInformation', function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var objectId = req.body.objectId.split("-");
    functionTool.relateGoodsInformation(objectId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/admin', function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var userOId = req.body.userOId;
    var nickName = req.body.nickName;
    functionTool.adminUser(userOId, nickName, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/admin/add', function (req, res) {
    res.render("admin/add.ejs", {})
});


router.post('/admin/addUser', function (req, res) {
    req.params = req.body;
    functionTool.addAdmin(req, function (err, result) {
        res.send();
    })
});

router.get('/admin/edit', function (req, res) {
    let objectId = req.query.id;
    functionTool.adminUser(objectId, "", "", "", "", function (err, result) {
        res.render("admin/edit", {"result": result});
    })
});

function saveImage(imagePath) {
    if (imagePath != "" && imagePath != null) {
        return new Promise((resolve, reject) => {
            fs.readFile(imagePath, function (err, data) {
                resolve(data);
            })
        }).then((filedata) => {
            let key = uuid.v1().replace(/-/g, "") + ".jpg";
            var file = new AV.File(key, filedata);
            return file.save().then(function (file) {
                console.log(file.id)
                return file;
            }, (error) => {
                console.log(error);
                return
            })
        })
    } else {
        return;
    }
}
router.post('/allow/adminLogin', function (req, res) {
    req.params = req.body;
    functionTool.addAdmin(req, function (err, result) {
        if (err) {
            res.send("0");
        } else {
            if (result == 10001) {
                res.send("1")
            } else if (result == 10003) {
                res.send("2")
            }
        }
    })
});

router.post('/wxGroup/list/type', function (req, res) {
    var objectId = req.body.objectId;
    var name = req.body.name;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.wxGroupType(objectId, name, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/wxGroup/list/belong', function (req, res) {
    var wxGroupType = req.body.wxGroupType;
    var name = req.body.name;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var objectId = req.body.objectId;

    functionTool.wxGroupTypeBelong(wxGroupType, name, objectId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});
router.get('/wxGroup/type/add', function (req, res) {
    res.render('wxGroup/addGroupType', {})
});


router.get('/wxGroup/add', function (req, res) {
    var groupType = req.query.groupType;
    res.render('wxGroup/addGroup', {groupType: groupType})
});

router.get('/wxGroup/edit', function (req, res) {
    var objectId = req.query.objectId;
    functionTool.wxGroupTypeBelong("", "", objectId, "", "", function (err, result) {
        res.render('wxGroup/editGroup', {result: result});
    })
});

router.get('/wxGroup/type/edit', function (req, res) {
    var objectId = req.query.objectId;
    functionTool.wxGroupType(objectId, "", "", "", function (err, result) {
        res.render('wxGroup/editGroupType', {result: result});
    })
});
router.post('/wxGroup/add', function (req, res) {
    // functionTool.wxGroupChange(req,(err,result)=>{
    //     if (err){
    //         res,send('2')
    //     }else{
    //         res.send('1')
    //     }
    // })
    var base64 = req.body.base64;
    var name = req.body.name;
    var objectId = req.body.objectId;
    var groupType = req.body.groupType;
    functionTool.wxGroupChange(base64, name, objectId, groupType, function (err, result) {
        if (err) {
            res.send('2')
        } else {
            res.send('1')
        }
    })
});

router.post('/wxGroupType/add', function (req, res) {
    req.params = req.body;
    functionTool.wxGroupoTypeChange(req, (err, result) => {
        if (err) {
            res, send('2')
        } else {
            res.send('1')
        }
    })
});

router.post('/wxGroupType/edit', function (req, res) {
    req.params = req.body;
    functionTool.wxGroupoTypeUpdate(req, (err, result) => {
        if (err) {
            res, send('2')
        } else {
            res.send('1')
        }
    })
});
router.post('/wxGroupType/remove', function (req, res) {
    var objectId = req.body.objectId;
    var todo = AV.Object.createWithoutData('wx_group_type', objectId);
    todo.destroy().then(function (success) {
        res.send('1')
    }, function (error) {
        res.send("2");
    });
})

router.post('/wxGroup/remove', function (req, res) {
    console.log("aa")
    var objectId = req.body.objectId;
    var todo = AV.Object.createWithoutData('wx_group', objectId);
    todo.destroy().then(function (success) {
        res.send('1');
    }, function (error) {
        res.send("2");
    });
})

router.post('/classification/list', function (req, res) {
    var objectId = req.body.objectId;
    var typeName = req.body.typeName;
    var type = req.body.type;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.shopTypeList(objectId, type, typeName, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});


//findForTemplate
router.post('/findForTemplate',async function(req,res){
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var result =  await functionTool.findTemplateForThread(objectId,page,num);
    res.send(JSON.stringify(result));

})

router.get('/templateForThreadAdd',function (req,res) {
    let objectId =req.query.objectId;
    res.render('smallRoutineVersion/templateAdd',{webAppOId:objectId});
})

router.post('/templateForThreadAdd' ,async function (req,res) {
    let webappOId = req.body.webappOId;
    let content = req.body.content;
    let name = req.body.name;
    let result = await  functionTool.addTemplateForThread(webappOId,content,name);
    if(result){
        res.send("1");
    }else{
        res.send("2");
    }
})

router.get('/temEdit',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.selTemplateForThread(objectId);
    res.render("smallRoutineVersion/templateEdit",{result:result});
})

router.post('/templateForThreadEdit',async function (req,res) {
    let objectId = req.body.objectId;
    let content = req.body.content;
    let name = req.body.name;
    let result = await functionTool.editTemplateForThread(objectId,content,name);
    if(result){
        res.send("1");
    }else{
        res.send("2");
    }
})
router.post('/temDelete', function (req,res) {
    let objectId = req.body.objectId;
    functionTool.deleteTemplateForThread(objectId,function (err,result) {
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})
router.post('/getUserIdentifyProp',async function (req,res) {
    let data = {}
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await functionTool.getUserIdentifyProp(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send("error");
    }
})

router.post('/userIdentifyPropAdd',async function (req,res) {
    var data = {}
    data.name = req.body.name
    data.type = req.body.type
    data.category = req.body.category
    data.tableField = req.body.tableField
    // console.log(req.body)
    let result = await functionTool.userIdentifyPropAdd(data);
    if(result){
        res.send('1');
    }else{
        res.send("0");
    }
})
router.get('/userIdentifyPropEdit',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.getUserIdentifyPropForId(objectId);
    res.render("edit/userIdentifyPropEdit",{result:result});
})
router.post('/userIdentifyPropUpdate',async function (req,res) {
    var data = {}
    data.objectId = req.body.objectId
    data.name = req.body.name
    data.category = req.body.category
    data.type = req.body.type
    data.status = req.body.status
    data.tableField = req.body.tableField
    let result = await functionTool.userIdentifyPropUpdate(data);
    if(result){
        res.send('1');
    }else{
        res.send("0");
    }
})

router.post('/getUserIdentifyPropRelation',async function (req,res) {
    let data = {}
    data.objectId = req.body.objectId;
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await functionTool.getUserIdentifyPropRelation(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.post('/userIdentifyPropRelationAdd',async function (req,res) {
    var data = {}
    data = req.body
    let result = await functionTool.userIdentifyPropRelationAdd(data);
    if(result){
        res.send('1');
    }else{
        res.send("0");
    }
})

router.post('/userIdentifyPropRelationRemove', function (req,res) {
    let objectId = req.body.objectId;
    functionTool.userIdentifyPropRelationRemove(objectId,function (err,result) {
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})

router.post('/getIntegralRatio',async function (req,res) {
    let data = {}
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await functionTool.getIntegralRatio(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.get('/integralRatioEdit',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.getIntegralRatioForId(objectId);
    res.render("integralRatio/integralRatioEdit",{result:result});
})
router.post('/integralRatioUpdate',async function (req,res) {
    var data = req.body
    let result = await functionTool.integralRatioUpdate(data);
    if(result){
        res.send('1');
    }else{
        res.send("0");
    }
})
router.post('/classification/goods/list', function (req, res) {
    var objectId = req.body.objectId;
    var shopType = req.body.shopType;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.shopTypeGoodsList(objectId, shopType, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});
router.get('/classification/goods', function (req, res) {
    var shopTypeOId = req.query.shopType;
    res.render("classification/goodsList", {shopTypeOId: shopTypeOId})
});

router.post('/classification/goods/add', function (req, res) {
    var shopTypeOId = req.body.shopTypeOId;
    var shopGoodsOId = req.body.shopGoodsOId;
    functionTool.classificationGoodsAdd(shopTypeOId, shopGoodsOId, (err, result) => {
        if (!err) {
            if (result == 10001) {
                res.send("1");
            } else {
                res.send("2");
            }
        } else {
            res.send("0")
        }
    })
});

router.get('/class/add', function (req, res) {
    var type = req.query.classType;
    res.render("classification/classificationAdd", {type: type})
});

router.get('/banner/addBanner', function (req, res) {
    let {objectId} = req.query
    res.render("shop/banner/addBanner", {objectId: objectId})
});

router.get('/banner/editBanner', function (req, res) {
    let {objectId} = req.query
    functionTool.fetchGoodsBannerById(objectId, ( result) => {

        res.render("shop/banner/editBanner", {result: result})

    })


});




router.get('/addBannerRelationGoods', function (req, res) {
    let {bannerOId} = req.query
    res.render("shop/banner/addBannerRelationGoods", {objectId: bannerOId})
});


// router.post('/classification/add',function (req,res) {
//     var form = new multiparty.Form();
//     form.parse(req,function (err,fields,files) {
//         var typeName = fields.typeName[0];
//         var type = fields.type[0];
//         var pic =   files.Fdata[0];
//         var key = uuid.v1().replace(/-/g, "")+".png";
//         qn.uploadImg(pic.path,key,function (err,result) {
//             if(result==200){
//                 var ShopTypes = AV.Object.extend("Shop_type");
//                 var ShopType = new ShopTypes();
//                 ShopType.set("typeName",typeName);
//                 ShopType.set("type",type);
//                 ShopType.set("picURL",key);
//                 ShopType.save().then(function (shop) {
//                     res.send("1");
//                 })
//             }
//         })
//     })
// });
router.post('/classification/add', function (req, res) {
    functionTool.updateShopType(req, function (err, result) {
        console.log(err, result);
        if (!err) {
            res.send("1")
        }
    })
});

router.post('/banner/add', function (req, res) {
    console.log(req.body)
    functionTool.addBanner(req, function (err, result) {
        // console.log(err, result);
        if (!err) {
            res.send("1")
        }

    })
});
router.post('/banner/edit', function (req, res) {
    console.log(req.body)
    functionTool.editBanner(req, function (err, result) {
        // console.log(err, result);
        if (!err) {
            res.send("1")
        }

    })
});

router.get('/class/edit', function (req, res) {
    var objectId = req.query.id;
    functionTool.shopTypeList(objectId, "", "", "", "", function (err, result) {
        res.render("classification/classificationEdit", {result: result})
    })
});

router.post('/class/remove', function (req, res) {
    var objectId = req.body.objectId;
    var status = req.body.status;
    var ShopType = AV.Object.createWithoutData("Shop_type", objectId);
    ShopType.set("status", status)
    ShopType.save().then(function (result) {
        res.send("1")
    }, function (reject) {
        res.send("0")
    })
});

router.post('/classification/goods/remove', function (req, res) {
    var objectId = req.body.objectId;
    var status = req.body.status;
    var ShopType = AV.Object.createWithoutData("Shop_type_good_relation", objectId);
    ShopType.set("status", status)
    ShopType.save().then(function (result) {
        res.send("1")
    }, function (reject) {
        res.send("0")
    })
});

router.post('/usersInformation/cache/remove',  function (req, res) {
    var objectId = req.body.objectId;
    redisServer.delRedisContent(keys['userTribe'] +objectId,function (err,myTribe) {
        if(err){
            console.log(err);
            res.send("2");
        }else {
            res.send("1");
        }
    })
});

router.post('/version/ios', function (req, res) {
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.iosVersion(objectId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/smallRoutineVersion', async function (req, res) {
    let {objectId} = req.body;
    let page = req.body.pageIndex;
    page = Number(page) + 1;
    let num = req.body.pageSize;
    let result = await  functionTool.weAppVersion(objectId, page, num)
    res.send(JSON.stringify(result));

});

router.get('/smallRoutineVersion/edit', async function (req, res) {
    let {objectId} = req.query;
    let result = await functionTool.weAppVersion(objectId);
    res.render("smallRoutineVersion/smallAdd", {result: result})
});

router.post('/update/smallRoutine', async function (req, res) {
    req.params = req.body;
    let result = await  functionTool.updateWeApp(req);
    if (result) {
        res.send("1")
    }
});

router.post('/version/android', function (req, res) {
    var objectId = req.body.objectId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var versionName = req.body.versionName;
    var versionNo = req.body.versionNo;
    functionTool.androidVersion(objectId, versionName, versionNo, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/version/android/add', async function (req, res) {
    var config = {
        'AccessKey': 'AsPvgPQZqIPBojLgMm6HixsjsIz7YCEy1gNli9Zb',  // https://portal.qiniu.com/user/key
        'SecretKey': 'cJ47G1jJPzC20260pxlt9uh4ScUV51MlU7iMvhC9',
        'Bucket': 'android',
        'Port': 19110,
        'UptokenUrl': 'uptoken',
        'Domain': 'http://7xiuo5.com1.z0.glb.clouddn.com/' // bucket domain eg:http://qiniu-plupload.qiniudn.com/
    };
    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0,
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var token = putPolicy.uploadToken(mac);
    res.render('version/androidAdd', {
        domain: config.Domain,
        uptoken: token
    });
});


router.post('/update/android', function (req, res) {
    req.params = req.body;
    functionTool.updateAndroid(req, function (err, result) {
        if (!err) {
            res.send("1")
        }
    })
});


router.get('/version/ios/edit', function (req, res) {
    var objectId = req.query.objectId;
    functionTool.iosVersion(objectId, "", "", function (err, result) {
        res.render("version/iosAdd", {result: result})
    })
});

router.post('/update/ios', function (req, res) {
    req.params = req.body;
    functionTool.updateIos(req, function (err, result) {
        if (!err) {
            res.send("1")
        }
    })
});

router.get('/getQiniuToken', async function (req, res, next) {
    var token = await qnAndroid.uploadToken();
    res.header("Cache-Control", "max-age=0, private, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    if (token) {
        res.json({
            uptoken: token
        });
    }
});


router.post('/userAddress', function (req, res) {
    var userOId = req.body.userOId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.receiveAddress(userOId, "", page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get('/userAddress/add', async function (req, res) {
    var userOId = req.query.userOId;
    res.render('edit/userAddressAdd', {
        userOId: userOId,
    });
});

router.post('/updateUserAddress', function (req, res) {
    req.params = req.body;
    functionTool.updateUserAddress(req, function (err, result) {
        if (!err) {
            res.send("1")
        }
    })
});

router.get('/userAddress/edit', async function (req, res) {
    var objectId = req.query.objectId;
    functionTool.receiveAddress("", objectId, "", "", function (err, result) {
        res.render('edit/userAddressEdit', {
            result: result,
        });
    })
});

router.post('/userFriends', function (req, res) {
    var userOId = req.body.userOId;
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    functionTool.userFriends(userOId, "", page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});


router.get('/goodsAdd', function (req, res, next) {
    var config = qn.config;
    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0,
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var token = putPolicy.uploadToken(mac);
    functionTool.goodsTypeSelect(function (result) {
        res.render('mall/goodsMangerAdd', {
            domain: config.Domain,
            uptoken: token,
            goodsTypes:JSON.stringify(result)
        });
    })

});

router.post('/account/total', function (req, res) {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var userOId = req.body.userOId;
    var objectId = req.body.objectId;
    var nickName = req.body.nickName;
    functionTool.userShopAccount(userOId, objectId, nickName, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/auth/idCardVer', function (req, res) {
    var idCard = req.body.idCard;
    functionTool.userLevelInformation("", "", "", "", idCard, "", "", "", "", function (err, result) {
        res.send(JSON.stringify(result));
    })
});

router.get("/live/goods", (req, res) => {
    var tribeOId = req.query.tribeOId;
    var objectId = req.query.objectId;
    console.log()
    res.render('live/goodsAdd', {
        tribeOId: tribeOId,
        objectId: objectId
    });

})

router.post("/live/goods/list", (req, res) => {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var tribeOId = req.body.tribeOId;
    var objectId = req.body.objectId;
    var title = req.body.title;
    var goodsOId = req.body.goodsOId;
    console.log(req.body)
    functionTool.shopTribeGoods(objectId, tribeOId, title, goodsOId, page, num, function (err, result) {
        res.send(JSON.stringify(result));
    })
})
router.post("/live/goods/add", (req, res) => {
    var objectId = req.body.objectId;
    var goodsOId = req.body.goodsOId;
    console.log(goodsOId);
    var live = AV.Object.createWithoutData("Live_room", objectId);
    var goods = AV.Object.createWithoutData("Shop_goods", goodsOId)
    live.add('goods', goods);
    live.save().then(result => {
        res.send("1")
        console.log(result.id);
    }, reject => {
        console.log(reject)
    })
})

router.post("/live/goods/remove", (req, res) => {
    var objectId = req.body.objectId;
    var goodsOId = req.body.goodsOId;
    console.log(goodsOId);
    var live = AV.Object.createWithoutData("Live_room", objectId);
    var goods = AV.Object.createWithoutData("Shop_goods", goodsOId)
    live.remove('goods', goods);
    live.save().then(result => {
        res.send("1")
        console.log(result.id);
    }, reject => {
        console.log(reject)
    })
})

router.post("/live/bindGoods", (req, res) => {
    var page = req.body.pageIndex;
    page = Number(page) + 1;
    var num = req.body.pageSize;
    var objectId = req.body.objectId;
    functionTool.liveBindGoods(objectId, page, num, function (err, result) {
        console.log(result)
        res.send(JSON.stringify(result));
    })
})

//调查问卷
router.post('/questionManger',async function (req,res) {
    let page = req.body.pageIndex;
    let params = {}
    params.page = Number(page) + 1;;
    params.pageSize = req.body.pageSize;
    params.type = req.body.type;
    params.title = req.body.title;
    params.url = req.body.url;

    let result = await functionTool.getQuestion(params);
    if (result){
        res.send(JSON.stringify(result));
    }
})
router.post('/questionAdd',async function (req,res) {
    let params = {}
    params.type = req.body.type;
    params.title = req.body.title;
    params.url = req.body.url;
    let result = await functionTool.questionAdd(params);
    if (result){
        res.send(JSON.stringify(result));
    }
})
router.get('/questionEdit', async function (req, res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.questionEdit(objectId);
    res.render('question/questionEdit', {result: result})
})

router.post('/questionUpdate',async function (req,res) {
    let params = {}
    params.objectId = req.body.objectId;
    params.type = req.body.type;
    params.title = req.body.title;
    params.url = req.body.url;
    let result = await functionTool.questionUpdate(params);
    if (result){
        res.send('1');
    } else {
        res.send('0');
    }
})
router.post('/questionRemove', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.questionRemove(objectId);
    // res.send(JSON.stringify(result));
    if (result){
        res.send('1');
    } else {
        res.send('0');
    }
})
router.post('/getGoodsTribeCorrelation',async function (req,res) {
    let data = {}
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await functionTool.getGoodsTribeCorrelation(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.post('/goodsTribeCorrelationAdd',async function (req,res) {
    let params = req.body
    let result = await functionTool.goodsTribeCorrelationAdd(params);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.post('/goodsTribeCorrelationDel', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.goodsTribeCorrelationDel(objectId);
    // res.send(JSON.stringify(result));
    if (result){
        res.send(JSON.stringify(result));
    } else {
        res.send({});
    }
})

router.post('/getDeviceLiveUrlForIp', async function (req, res) {
    let rtmpUrl = req.body.rtmpUrl;
    // console.log(rtmpUrl)
    let result = await  functionTool.getDeviceLiveUrlForIp(rtmpUrl);
    if (result){
        // console.log(result)
        res.send(result);
    } else {
        res.send({});
    }U
})
router.post('/getUserInviteFriends',async function (req,res) {
    let data = {}
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    data.nickName = req.body.nickName;
    data.mobilePhoneNumber = req.body.mobilePhoneNumber;
    let result = await functionTool.getUserInviteFriends(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})

router.post('/userInviteFriendsDel', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.userInviteFriendsDel(objectId);
    if (result == objectId){
        res.send(JSON.stringify(result));
    } else {
        res.send({});
    }
})
router.post('/getSystemSendScoreList', async function (req, res) {
    let data = {}
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    data.userOId = req.body.userOId;
    data.nickName = req.body.nickName;
    data.mobilePhoneNumber = req.body.mobilePhoneNumber;
    let result = await functionTool.getSystemSendScoreList(data);
    if(result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.get('/addSystemSendScore', async function (req, res) {
    res.render('edit/systemSendScoreAdd', {})
})
router.post('/systemSendScoreAdd',async function (req,res) {
    let params = req.body
    let result = await functionTool.systemSendScoreAdd(params);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})

router.post('/systemSendScoreDel', async function (req, res) {
    let data = req.body
    let result = await  functionTool.systemSendScoreDel(data);
    if (result == data.objectId){
        res.send(JSON.stringify(result));
    } else {
        res.send({});
    }
})

router.get("/shopPopUpLogoMangerAdd", function (req, res) {
    //token
    var config = qn.liveConfig;

    var options = {
        scope: config.Bucket,
        deleteAfterDays: 0
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    //Logo图token
    var token = putPolicy.uploadToken(mac);
    var configPic = qn.config;
    var optionsPic = {
        scope: configPic.Bucket,
        deleteAfterDays: 0,
    }
    var putPolicyPic = new qiniu.rs.PutPolicy(optionsPic);
    var macPic = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
    var tokePic = putPolicyPic.uploadToken(macPic);
    res.render('mall/shopPopUpLogoMangerAdd', {
        domain: config.Domain,
        uptoken: token,
        uptokenPic: tokePic,
    });
});
router.post('/getShopPopUpLogo',async function (req,res) {
    let page = req.body.pageIndex;
    page = Number(page)+1;
    let num =  req.body.pageSize;
    let goodsInShopType = req.body.goodsInShopType
    let result = await functionTool.getShopPopUpLogo(page,num,goodsInShopType);
    res.send(JSON.stringify(result));
})

router.post('/scoreShopGoodSelect',async function (req,res) {
    let data = {}
    if (req.body.name){
        data.name = req.body.name;
    }
    if (req.body.objectId){
        data.objectId = req.body.objectId;
    }
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await  functionTool.scoreShopGoodSelect(data);
    res.send(JSON.stringify(result));
})
router.post('/scoreShopGoodSelectNoGroup',async function (req,res) {
    let data = {}
    if (req.body.name){
        data.name = req.body.name;
    }
    if (req.body.objectId){
        data.objectId = req.body.objectId;
    }
    let page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    let result = await  functionTool.scoreShopGoodSelectNoGroup(data);
    res.send(JSON.stringify(result));
})
router.post("/addShopPopUpLogo", function (req, res) {
    let params = req.body;
    // console.log(params,'---')

    functionTool.addShopPopUpLogo(params, result=> {
        if (result) {
            res.send(JSON.stringify(result));getBusinessCollegeSubList
        } else {
            res.send();
        }
    });
});
router.post('/delShopPopUpLogo', async function (req, res) {
    let objectId = req.body.objectId;
    let result = await  functionTool.delShopPopUpLogo(objectId);
    if (result == objectId){
        res.send(JSON.stringify(result));
    } else {
        res.send({});
    }
})

router.post('/parentGoodsTypeTree', function (req, res) {
    functionTool.getParentGoodsType(function (result) {
        res.send(JSON.stringify(result));
    })
});


/**
 * 获取没有父节点的所有商品分类
 */
router.post('/parentGoodsTypeTreeWithoutParent', function (req, res) {
    functionTool.parentGoodsTypeTreeWithoutParent(function (result) {
        res.send(JSON.stringify(result));
    })
});


router.post('/fetchGoodsTypeBanners', function (req, res) {
    functionTool.fetchGoodsTypeBanners(req.body,function (result) {
        res.send(JSON.stringify(result));
    })
});
router.post('/fetchBannerRelationGoods', function (req, res) {
    functionTool.fetchBannerRelationGoods(req.body,function (result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/banner/addBannerGoodsRelation', function (req, res) {
    functionTool.addBannerGoodsRelation(req.body,function (result) {
        res.send(JSON.stringify(result));
    })
});

router.post('/banner/removeBannerRelationGoods', function (req, res) {
    functionTool.removeBannerRelationGoods(req.body,function (result) {
        res.send(JSON.stringify(result));
    })
});
router.post('/banner/removeGoodsBanner', function (req, res) {
    functionTool.removeGoodsBanner(req.body,function (result) {
        res.send(JSON.stringify(result));
    })
});


// router.post('/getChildGoodsType', function (req, res) {
//   let parentId = req.body.parentId
//   console.log(parentId)
//   functionTool.getChildGoodsType(parentId,function (result) {
//     res.send(JSON.stringify(result));
//   })
// });
router.post('/getGoodsType', function (req, res) {
    // var sysCategory = req.body.dept_id;
    let data = {}
    data.parentId = req.body.parentId;
    var page = req.body.pageIndex;
    data.page = Number(page) + 1;
    data.num = req.body.pageSize;
    functionTool.getGoodsType(data, function (result) {
        res.send(JSON.stringify(result));
    })
});
router.get('/goodsTypeMangerAddForParent', function (req, res, next) {
    res.render('mall/goodsTypeMangerAddForParent');
});
router.get('/goodsTypeMangerAddForChild', function (req, res, next) {
    // console.log(req.query)
    res.render('mall/goodsTypeMangerAddForChild',{
        parentId:req.query.parentId,
        parentName:req.query.parentName
    });
});
// router.get('/goodsTypeMangerAddForParent', function (req, res, next) {
//   var config = qn.config;
//   var options = {
//     scope: config.Bucket,
//     deleteAfterDays: 0,
//   };
//   var putPolicy = new qiniu.rs.PutPolicy(options);
//   var mac = new qiniu.auth.digest.Mac(config.AccessKey, config.SecretKey);
//   var token = putPolicy.uploadToken(mac);
//   res.render('mall/goodsTypeMangerAddForParent', {
//     domain: config.Domain,
//     uptoken: token,
//   });
// });
// router.post('/addParentGoodsType', async function (req, res) {
//   let result = await functionTool.addParentGoodsType(req.body)
//   console.log(result)
//
//   // functionTool.addParentGoodsType(req.body, function (result) {
//   //   if (!err) {
//   //     res.send('1');
//   //   } else {
//   //     res.send('0');
//   //   }
//   // })
//   // }
// })
router.post('/goodsTypeIconUpload', upload.single('image'), function (req, res, next) {
    var uploadFilePath = req.file.path;
    var filename = req.file.filename;
    if (req.file) {
        fs.readFile(uploadFilePath, function (err, data) {
            // console.log(err);
            // console.log(data);
            var file = new AV.File(filename, data);
            file.save().then(function (file_) {
                // 文件保存成功
                // console.log(file_.url());
                // console.log(file_.id);

                fs.unlink(uploadFilePath, function (error) {
                    if (error) {
                        console.log(error,'删除-1-1-1-');
                    }
                })
                let data = {}
                data.name = req.body.name;
                data.parentId = req.body.parentId
                data.iconId = file_.id;
                data.iconObj = file_
                functionTool.addGoodsType(data,result=>{
                    if (result){
                        res.send('分类添加成功！')
                    }else{
                        res.send('分类添加失败！')
                    }
                })
            }, function (error) {
                // 异常处理
                console.error(error,'0-0--00-0-0-0');
            });
        });
    } else {
        console.log('文件不存在')
    }
});
router.get('/goodsTypeMangerEdit', function (req, res, next) {
    let objectId = req.query.objectId
    functionTool.getGoodTypeForOId(objectId,result=>{
        res.render('mall/goodsTypeMangerEdit',{result:result});
    })

});
router.post('/editGoodsType', function (req, res) {
    functionTool.editGoodsType(req.body, function (result) {
        res.send(JSON.stringify(result));
    })
});
router.post('/delGoodsType', async function (req, res) {
    let objectId = req.body.objectId
    let result = await functionTool.delGoodsType(objectId)
    res.send(JSON.stringify(result));
    // functionTool.delGoodsType(objectId, function (result) {
    //   res.send(JSON.stringify(result));
    // })
});


router.get('/shopIntergationSelectGoodsType', function(req, res, next) {
    res.render('mall/shopIntergationSelectGoodsType', {});
});

router.post('/selectGoodsTypeForShopIntergation', function (req, res) {
    functionTool.selectGoodsTypeForShopIntergation(function (result) {
        res.send(JSON.stringify(result))
    })
});
router.post('/getBusinessCollegeClassify',async function (req,res) {
    let params = req.body
    let result = await functionTool.getBusinessCollegeClassify(params);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})

router.post('/getBusinessCollegeSubList',async function (req,res) {
    var objectId = req.body.objectId;
    var pageIndex = req.body.pageIndex;
    var pageSize = req.body.pageSize;
    let result = await functionTool.getBusinessCollegeSubList(objectId,pageIndex,pageSize);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.post('/deleteBusinessCollegeSubItem',async function (req,res) {
    var objectId = req.body.objectId;
    let result = await functionTool.deleteBusinessCollegeSubItem(objectId);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
router.post('/addBusinessCollegeSubItem',async function (req,res) {
    let result = await functionTool.addBusinessCollegeSubItem(req.body);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})

router.post('/editBusinessCollegeSubItem',async function (req,res) {
    let result = await functionTool.editBusinessCollegeSubItem(req.body);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})


router.post('/groupGoodsSearch',async function (req,res) {
    let page = req.body.pageIndex;
    page = Number(page)+1;
    let num =  req.body.pageSize;
    let goodsName = req.body.goodsName;
    let goodsParentTypeID = req.body.goodsParentTypeID;
    let result = await functionTool.groupGoodsSearch(page,num,goodsName,goodsParentTypeID);
    res.send(JSON.stringify(result));
})
/**
 * 添加拼团活动
 */
router.post('/addGroupActivity',async function (req,res) {
    let scoreShopGoodsOId=req.body.scoreShopGoodsOId;
    let groupPrice=req.body.groupPrice;
    let groupScore=req.body.groupScore;
    let groupPeopleNum=req.body.groupPeopleNum;
    let limitNum=req.body.limitNum;
    let minGroupPeopleNum=req.body.minGroupPeopleNum;
    let groupDuration=req.body.groupDuration;
    let groupStartTime=req.body.groupStartTime;
    let groupEndTime=req.body.groupEndTime;
    if(!scoreShopGoodsOId||scoreShopGoodsOId==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!scoreShopGoodsOId||scoreShopGoodsOId==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupPrice||groupPrice==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupScore||groupScore==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupPeopleNum||groupPeopleNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!limitNum||limitNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!minGroupPeopleNum||minGroupPeopleNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupDuration||groupDuration==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupStartTime||groupStartTime==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupEndTime||groupEndTime==""){
        return res.send(JSON.stringify("参数错误"));
    }
    let result = await functionTool.addGroupActivity(req);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})
/**
 * 删除拼团活动
 */
router.post('/deleteGroupActivity',async function (req,res) {

    functionTool.deleteGroup(req,function (err,result) {
        console.log(result);
        if (err) {
            res.send(err);
        } else {
            res.send("10001");
        }
    });
})
/**
 * 跳转编辑拼团活动页面
 */
router.get('/editGroupActivity',async function (req,res) {
    let objectId = req.query.objectId;
    let result = await  functionTool.selectScoreShopGoods(objectId);
    res.render('group/editGroupActivity',{result:result});
})
/**
 * 编辑拼团活动
 */
router.post('/editGroupActivityData',async function (req,res) {
    let objectId = req.body.objectId;
    let groupPrice=req.body.groupPrice;
    let groupScore=req.body.groupScore;
    let groupPeopleNum=req.body.groupPeopleNum;
    let limitNum=req.body.limitNum;
    let minGroupPeopleNum=req.body.minGroupPeopleNum;
    let groupDuration=req.body.groupDuration;
    let groupStartTime=req.body.groupStartTime;
    let groupEndTime=req.body.groupEndTime;

    if(!objectId||objectId==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupPrice||groupPrice==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupScore||groupScore==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupPeopleNum||groupPeopleNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!limitNum||limitNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!minGroupPeopleNum||minGroupPeopleNum==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupDuration||groupDuration==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupStartTime||groupStartTime==""){
        return res.send(JSON.stringify("参数错误"));
    }
    if(!groupEndTime||groupEndTime==""){
        return res.send(JSON.stringify("参数错误"));
    }
    let result = await functionTool.editGroupActivity(req);
    if (result){
        res.send(JSON.stringify(result));
    }else{
        res.send({});
    }
})

router.post('/groupSearch',async function (req,res) {
    console.log("groupSearch-->11")
    let result = await functionTool.groupSearch(req);
    console.log("groupSearch-->"+JSON.stringify(result))
    res.send(JSON.stringify(result));
})

router.post('/sameGroupOrder',async function (req,res) {
    let buyerOId=req.body.buyerOId
    let receiver=req.body.receiver
    let orderCode=req.body.orderCode
    let buyerNickName=req.body.buyerNickName
    let orderStatus=req.body.orderStatus

    let groupOId =  req.body.groupOId;
    console.log("sameGroupOrder-groupOId->"+groupOId)
    if(groupOId==""||!groupOId){
        return res.send(JSON.stringify("参数错误"));
    }
    console.log("sameGroupOrder-groupOId->"+groupOId)
    let result = await functionTool.sameGroupOrder(req);
    console.log("sameGroupOrder-->"+JSON.stringify(result))
    res.send(JSON.stringify(result));
})

//钱包管理
router.post('/getWalletInfo',async function (req,res) {
  let data = {}
  let page = req.body.pageIndex;
  data.page = Number(page) + 1;
  data.num = req.body.pageSize;
  let result = await functionTool.getWalletInfo(data);
  if(result){
    res.send(JSON.stringify(result));
  }else{
    res.send({});
  }
})
router.get('/addWalletAddress', function (req, res) {
  functionTool.getWalletTokenType(tokenTypeList=> {
    res.render("wallet/addWalletAddress", {result: JSON.stringify(tokenTypeList)})
  })
});
router.post('/walletAddressAdd', async function (req, res) {
  let result = await  functionTool.walletAddressAdd(req.body);
  if (result == req.userOId){
    res.send(JSON.stringify(result));
  } else {
    res.send({});
  }
})
router.post('/walletAddressRemove', async function (req, res) {
  let objectId = req.body.objectId
  let result = await  functionTool.walletAddressRemove(objectId);
  if (result == objectId){
    res.send(JSON.stringify(result));
  } else {
    res.send({});
  }
})
router.get('/showDistributeTokenInfo', function (req, res) {
  let objectId = req.query.id;
  functionTool.getWalletInfoForId(objectId,function (err, result) {

    functionTool.getWalletTokenType(tokenTypeList=> {

      res.render("wallet/distributeTokenInfo", {result: result,info:JSON.stringify(tokenTypeList)});
    });
  });
});

router.post('/distributeToken', async function (req, res) {

  let toAddress = req.body.walletAddress;
  functionTool.distributeToken(req.body,result=>{
    if (toAddress == result){
      res.send(JSON.stringify(result));
    } else {
      res.send({});
    }
  })
})
router.get('/showQueryAddressPageTx', async function (req, res) {
  let walletAddress = req.query.walletAddress;
  res.render("wallet/queryAddressPageTx", {result: JSON.stringify(walletAddress)});
})
router.post('/queryAddressPageTx', function (req, res) {
  let data = {}
  let page = req.body.pageIndex;
  data.page = Number(page) + 1;
  data.num = req.body.pageSize;
  data.walletAddress = req.body.walletAddress
  // console.log(data)
  functionTool.queryAddressPageTx(data,result=>{
    // console.log(result)
    if(result){
      res.send(JSON.stringify(result));
    }else{
      res.send({});
    }
  });
})
router.post('/getExternalGoodsInfo', async function (req, res) {

  let data = {}
  let page = req.body.pageIndex;
  data.page = Number(page) + 1;
  data.num = req.body.pageSize;
  data.sourceGoodsName = req.body.sourceGoodsName
  data.status = req.body.status
  data.goodsSource = req.body.goodsSource
  data.goodsTypeOId = req.body.goodsTypeOId
  data.goodsTypePId = req.body.goodsTypePId
  let result = await functionTool.getExternalGoodsInfo(data);
  if(result){
    res.send(JSON.stringify(result));
  }else{
    res.send({});
  }
})
var excelUploadFilePath = ''
var excelUploadFileName = ''
router.post('/excelUpload', upload.single('excelFile'), async function (req, res, next) {
  // console.log(req.file.path)
  // console.log(req.file.filename)
  excelUploadFilePath = req.file.path
  excelUploadFileName = req.file.filename
  // console.log(excelUploadFilePath)
  // console.log(excelUploadFileName)
});

router.post('/importExternalGoods', async function (req, res, next) {
  let data = {}
  data.uploadFilePath = excelUploadFilePath
  data.uploadFileName = excelUploadFileName
  data.goodsSource = req.body.goodsSource
  data.goodsTypeOId = req.body.goodsTypeOId
  data.goodsTypePId = req.body.goodsTypePId
  // console.log('importExternalGoodsData',data)
  let results = await functionTool.excelUpload(data)
  if (results){
    fs.unlink(excelUploadFilePath, function (error) {
      if (error) {
        console.log(error,'删除上传Excel失败！');
      } else {
        // res.render('mall/externalGoodsManger', {});
        excelUploadFilePath = ''
        excelUploadFileName = ''
        res.send('10000')
      }
    })
  } else {
    console.log('上传Excel失败！')
  }
});

router.post('/removeExternalGoods', async function (req, res) {
  let result = await functionTool.removeExternalGoods(req.body);
  if (result){
    res.send(JSON.stringify(result));
  } else {
    res.send({});
  }
})
router.get('/shopIntergationBatchAdd', function(req, res, next) {
  res.render('mall/shopIntergationBatchAdd', {});
});


module.exports = router;